<template>
  <el-dialog
    v-model="createVisible"
    :title="operation == 'create' ? '添加商品分类' : '编辑商品分类'"
    @before-ok="createOk"
    @close="close(createRef)"
    top="100px"
    width="700px"
    
  >
    <div style="width: 600px">
      <el-form
        :model="createForm"
        ref="createRef"
        :rules="createRules"
        label-width="130px"
        size="default"
        v-loading="initLoading"
      >
        <el-form-item label="父级分类：" prop="pid">
          <el-select v-model="createForm.pid" class="form-select-fil">
            <el-option
              v-for="item in parentTree"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分类名称：" prop="cate_name">
          <el-input
            v-model="createForm.cate_name"
            placeholder="请输入分类名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="分类图标：" prop="icon">
          <upload-btn
            v-model="createForm.icon"
            width="40px"
            height="40px"
            count="1"
          ></upload-btn>
          <help hideIcon>建议尺寸180*180</help>
        </el-form-item>
        <el-form-item label="分类大图：" prop="image">
          <upload-btn
            v-model="createForm.image"
            count="1"
            width="234px"
            height="170px"
          ></upload-btn>
          <help hideIcon>建议尺寸468*340</help>
        </el-form-item>

        <el-form-item label="状态：" prop="status">
          <el-radio-group v-model="createForm.status">
            <el-radio :label="0">关闭</el-radio>
            <el-radio :label="1">开启</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序：" prop="sort">
          <el-input-number v-model="createForm.sort" :min="0" :max="10000" />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="flex center">
        <el-button @click="createVisible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="btnLoading"
          :disabled="btnLoading"
          @click="createOk(createRef)"
          >确定</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts">
export default {
  name: "storeGoodsCateCreate",
};
</script>
<script lang="ts" setup>
import { ref, getCurrentInstance, nextTick, reactive } from "vue";
import type { FormInstance } from "element-plus";
import {
  createGoodsCate,
  updateGoodsCate,
  getGoodsCateSelectTree,
  getGoodsCateDetail,
} from "@/api/store/goods_cate";
import type { Result, ResultError } from "@/types";

const {
  proxy: { $message, $utils },
} = getCurrentInstance() as any;

const emit = defineEmits(["success"]);

const createVisible = ref<boolean>(false);

const operation = ref<string>("create");

const operationId = ref<number>(0);

const createRef = ref<typeof FormInstance>();

const btnLoading = ref<boolean>(false);

const parentTree = ref<any>([]);

const initLoading = ref<boolean>(true)

const toInit = () => {
  initCascader();
  if (!operationId.value) {
    initLoading.value = false
    return;
  }
  getGoodsCateDetail({ id: operationId.value })
    .then((res: Result) => {
      createForm.value.cate_name = res.data.cate_name;
      createForm.value.pid = res.data.pid;
      createForm.value.icon = res.data.icon;
      createForm.value.image = res.data.image;
      createForm.value.sort = res.data.sort;
      createForm.value.status = res.data.status.value;
      initLoading.value = false
    })
    .catch((err: ResultError) => {
      $utils.errorMsg(err);
    });
};

const initCascader = () => {
  let obj: any = {};
  if (operationId.value) {
    obj["pid"] = operationId.value;
  }
  getGoodsCateSelectTree(obj)
    .then((res: Result) => {
      parentTree.value = res.data;
    })
    .catch((err: ResultError) => {
      $utils.errorMsg(err);
    });
};

const createForm = ref({
  pid: null,
  cate_name: "",
  sort: 0,
  status: 1,
  icon: "",
  image: "",
});
const createRules: any = reactive({
  cate_name: [{ required: true, message: "分类名称不能为空！" }],
  icon: [{ required: true, message: "分类图标不能为空！" }],
  image: [{ required: true, message: "分类大图不能为空！" }],
});

const createOk = async (formEl: typeof FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid: any, fields: any) => {
    if (valid) {
      if (btnLoading.value) {
        return;
      }
      btnLoading.value = true;
      let operationApi: any = null;
      if (operation.value == "create") {
        operationApi = createGoodsCate(createForm.value);
      } else {
        operationApi = updateGoodsCate(
          Object.assign(
            {
              id: operationId.value,
            },
            createForm.value
          )
        );
      }
      operationApi
        .then((res: Result) => {
          $message.success(res.message);
          close(formEl);
          emit("success");
          btnLoading.value = false;
        })
        .catch((err: ResultError) => {
          $utils.errorMsg(err);
          btnLoading.value = false;
        });
    }
  });
};

const open = (id: number = 0) => {
  initLoading.value = true
  if (id != 0) {
    operation.value = "update";
    operationId.value = id;
  } else {
    operation.value = "create";
  }
  nextTick(() => {
    toInit();
  });
  createVisible.value = true;
};

const close = async (formEl: typeof FormInstance | undefined) => {
  if (formEl) {
    formEl.resetFields();
  }
  operationId.value = 0;
  createVisible.value = false;
};

defineExpose({ open });
</script>